package com.code.user.config.token;

import com.code.user.service.impl.AccountServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.TokenGranter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: Yan
 * @date: 2023/4/14
 *
 * TokenGranter 扩展，将自定义的 grant_type 类型添加到 oauth2 中
 * 使用方法:
 * 在 configure(AuthorizationServerEndpointsConfigurer endpoints) 中:
 *      获取自定义 tokenGranter
 *      TokenGranter tokenGranter = TokenGranterExt.getTokenGranter(authenticationManager, endpoints, baseRedis, userService);
 *      endpoints.tokenGranter(tokenGranter);
 */
public class TokenGranterExtend {

    public static TokenGranter getTokenGranter(final AuthenticationManager authenticationManager,
                                               final AuthorizationServerEndpointsConfigurer endpointsConfigurer,
                                               StringRedisTemplate stringRedisTemplate,
                                               AccountServiceImpl accountService){
        // 默认tokenGranter集合 security 自带的
        List<TokenGranter> granterList = new ArrayList<>(Collections.singletonList(endpointsConfigurer.getTokenGranter()));
        // 使用默认的用户名密码登录
        // granterList.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, endpointsConfigurer.getTokenServices(), endpointsConfigurer.getClientDetailsService(), endpointsConfigurer.getOAuth2RequestFactory()));

        // 添加图形验证码
        granterList.add(new CaptchaTokenGranter(authenticationManager, stringRedisTemplate, endpointsConfigurer.getTokenServices(), endpointsConfigurer.getClientDetailsService(), endpointsConfigurer.getOAuth2RequestFactory()));

        // 添加短信验证码登录
        granterList.add(new SmsCodeTokenGranter(authenticationManager, stringRedisTemplate, accountService, endpointsConfigurer.getTokenServices(), endpointsConfigurer.getClientDetailsService(), endpointsConfigurer.getOAuth2RequestFactory()));
        return new CompositeTokenGranter(granterList);
    }

}
